<?php
// $_REQUEST is the global array that contains the submitted data.
// The array has an element for each form variable that was submitted.
// In our case we just have the text area, so count($_REQUEST) = 1.
// You can reference elements in the arrays by more than their numerical
// location.  You can call them by their "name". Ex: $_REQUEST["phylodata"]

function pv ($var)
{
	echo "<pre>";
	var_dump($var);  //var_dump is a php function that outputs array data and other objects in a readable way
	echo "</pre>";
}

$exploded_data = explode("\n", trim($_REQUEST["phylodata"]));  //trim is there to remove surrounding whitespace that otherwise causes viewer to choke.

for ($i = 0; $i < count($exploded_data); $i++)
{
	while(strpos($exploded_data[$i], "  ")) 
	{
		$exploded_data[$i] = str_replace("  ", " ", $exploded_data[$i]); 
	}
	$exploded_data[$i] = str_replace(" ", "\t", $exploded_data[$i]);  //convert all spaces to tabs for proper processing
	$exploded_data[$i] = explode("\t", $exploded_data[$i]);
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>Circle example using Google Maps GPolygon</title>
    <script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=ABQIAAAAxhj9keQ-W_pSFQOerM1zcxQDzKVN9nYxJYcr0zvm4oc_VslaGBS9ekLzJd0hyV9ctr3fGo93wfu7EA"
            type="text/javascript"></script>
    <link type="text/css" rel="stylesheet" href="javascripts/colorpicker/colorPicker.css" />
    <link type="text/css" rel="stylesheet" href="previewstyle.css" />
    <script src="javascripts/prototype.js" type="text/javascript"></script>
	<script type="text/javascript" src="javascripts/wz_jsgraphics.js"></script>
	<script type="text/javascript" src="javascripts/scriptaculous.js"></script>
	<script type="text/javascript" src="javascripts/colorpicker/yahoo.color.js"></script>
	<script type="text/javascript" src="javascripts/colorpicker/colorPicker.js"></script>
	<script type="text/javascript" src="phylogeovizmapfunctions.js"></script>
    <script type="text/javascript">
    //<![CDATA[
	//The above line is for XML parsers.  Just leave it.

	//GLOBAL VARIABLES
	var numpops;
	var numhaps;
	var pop_centers;
	var pop_haps;
	var radii_in_km = [40, 50, 65];
	var hap_colors;
	var pop_hapthetas;
	var map;
	var pop_radii;  //array of radii for each population
	var numbins = 3;  //number of different pie sizes
	var bindivs = [1, 5];  //array of boundary values for each of the bins.  Ex: if = [1, 5], there are 3 bins, <1, 2-5, 5+.  Note, count(bindivs) is always one smaller than numbins.
	var radii_in_px;  //array of radii for each pie size in pixels
	var pop_names;  //array of strings that store the names of each population.  The length of pop_names = numpops.

	function load() 
	{
      if (GBrowserIsCompatible()) 
      {
		//map and map features
        map = new GMap2(document.getElementById("map"));
        map.addControl(new GLargeMapControl());
        map.addControl(new GMapTypeControl());
        map.addControl(new GScaleControl());
        map.setCenter(new GLatLng(36.739067, -77.905517), 5);
        var givenmaptypes = map.getMapTypes();
 		map.setMapType(givenmaptypes[1]);  //google sometimes changes the variable names for the various maptypes, so it's best to check it this way.

	//get data saved from passed form elements.
<?php
	echo "numpops = ".count($exploded_data).";\n";
	echo "numhaps = ".(count($exploded_data[0])-3).";\n";
	echo "pop_names = new Array();\n";
	echo "pop_centers = new Array();\n";
	echo "pop_haps = new Array();\n";

	for ($i = 0; $i < count($exploded_data); $i++)
	{
		//if I had this to do over again, I would make the array index for pop_centers and pop_haps be the pop_name and then use foreach loops throughout the rest of the code.  But that would be too much work now, ah well...
		echo ("pop_names[".$i."] = \"{$exploded_data[$i][0]}\";\n");
		echo ("pop_centers[".$i."] = new GLatLng({$exploded_data[$i][1]}, {$exploded_data[$i][2]});\n");
		// '.' = append string, can't modify variables within the processed string
		echo "pop_haps[".$i."] = new Array();\n";
		for ($j = 3; $j < count($exploded_data[$i]); $j++)
		{
			echo ("pop_haps[".$i."].push({$exploded_data[$i][$j]});\n");
		}
	}
?>

		//set the view of the map to show all the populations
		var maxlat = maxmatrix(pop_centers, "lat");
		var maxlng = maxmatrix(pop_centers, "lng");
		var minlat = minmatrix(pop_centers, "lat");
		var minlng = minmatrix(pop_centers, "lng");
		var newbounds = new GLatLngBounds(new GLatLng(minlat-0.5, minlng-0.5), new GLatLng(maxlat+0.5, maxlng+0.5));
		map.setCenter(newbounds.getCenter());
		map.setZoom(map.getBoundsZoomLevel(newbounds));

        //Display the pies for the read in information previously processed by php.
        //The colors of the haplotypes are the same across populations.  

		//set pie sizes statically for now
		pop_radii = setdefaultradii(numpops, numhaps, pop_haps, numbins, bindivs, radii_in_km);
		
		//randomly generate haplotype colors
		hap_colors = new Array();
		for (var i = 0; i < numhaps; ++i)
		{
			hap_colors.push(RGB2Color(rand(255),rand(255),rand(255)));
			//stores the colors for each haplotype
		}

		//must convert pop_haps to appropriate pop_hapthetas
		pop_hapthetas = new Array();
		for (var i = 0; i < numpops; ++i)
		{
			pop_hapthetas[i] = new Array();
			pop_hapthetas[i].push(0);
			for (var j = 0; j < (numhaps - 1); ++j)
			{
				pop_hapthetas[i].push((pop_haps[i][j] * 360 / sumarray(pop_haps[i])) 
					+ pop_hapthetas[i][j]);		
			}
			pop_hapthetas[i].push(360);
			
			//draw the pie and make it draggable
			drawpie(map, i, pop_radii[i], pop_centers[i], pop_hapthetas[i], hap_colors);
		}

		radii_in_px = calc_radiiinpx(map, numbins, radii_in_km);
		drawpiesizelegend(numbins, bindivs, radii_in_px, "popsizelegend");  //draw sample size table divs

		var mapproj = G_NORMAL_MAP.getProjection();  //for fromPixelToLatLng(pixel, zoom,  unbounded?)

		//display hap color information to legend
		for (var h = 0; h < numhaps; ++h)
		{
			var swatchid = "hap"+(h)+"color";
			$(swatchid).value = hap_colors[h].substring(1, hap_colors[h].length);
			
			new Control.ColorPicker(swatchid, { IMAGE_BASE : "javascripts/colorpicker/img/", "swatch" : "colorbox"+(h), });
		}
		
		//register the updates to the haplotype colors and change the pie colors
		Event.observe($("colorpicker-okbutton"), "click", changeHapColor);



		// Make sure the map redraws the pies correctly on zooming
		GEvent.addListener(map, "zoomend", function (oldLevel, newLevel) 
		{
			//clear old pie info
			map.clearOverlays();

			clearpiedivs(numpops);

			//draw new pies
			for (var i = 0; i <numpops; ++i)
			{
				drawpie(map, i, pop_radii[i], pop_centers[i], pop_hapthetas[i], hap_colors);
			}

			//redraw the legend after zooming
			radii_in_px = calc_radiiinpx(map, numbins, radii_in_km);
			drawpiesizelegend(numbins, bindivs, radii_in_px, "popsizelegend");  
		});
      }  
    }

    //]]>
    </script>
  </head>

  <body onload="load()" onunload="GUnload()">
    <h2>Preview of your PhyloGeoViz map</h2>
    <div id="map" style="width: 800px; height: 500px"></div>
   	<div id="seccolumn">
   	<div id="legend">
   		<!-- have a div for each haplotype -->
   		<h2>Legend</h2>
   		<div id="hapcolorlegend">
   			<h3>Haplotype colors</h3>
   			<p>To edit a color, click on the appropriate colorbox.</p>
   			<table>
<?php	//create the divs and table elements for the haplotype color legend
	//the div background colors (and thus legend colors) will be generated using javascript upon loading (in load())
	for ($h = 0; $h < (count($exploded_data[0])-3); $h++)
	{
		echo "\t\t\t\t\t<tr><td>hap".($h)."</td>";
		echo "<td><input type=\"hidden\" id=\"hap".($h)."color\"> <button style=\"width: 1.5em; height: 1.5em; border: 1px outset #666;\" id=\"colorbox".($h)."\" class=\"colorbox\"></button></td></tr>\n";
	}
?>   		
	   		</table>
   		</div>
   		<div id="popsizelegend">
   			<h3>Sample sizes</h3>
		</div>
   	</div>

	<!-- Make buttons that control the size of the pies -->
	<div id="pieoptions">
   		<h2>Pie options</h2>
   		<table>
   		<tr>
   			<td><input type="button" id="piesmaller" name="piesmaller" value="-" onclick="piesize('-');">
				<input type="button" id="pielarger" name="pielarger" value="+" onclick="piesize('+');"></td>
			<td>Decrease or increase the size of the pies</td>
		</tr>
		</table>
   	</div>
   	<div id="exportoptions">
   		<h2>Export options</h2>
   		<form id="exportform" name="exportform" action="export.php" method="post">
			<input type="hidden" id="numpops" name="numpops">
			<input type="hidden" id="numhaps" name="numhaps">
			<input type="hidden" id="pop_names" name="pop_names">
			<input type="hidden" id="pop_centers" name="pop_centers">
			<input type="hidden" id="pop_haps" name="pop_haps">
			<input type="hidden" id="pop_radii" name="pop_radii">
			<input type="hidden" id="hap_colors" name="hap_colors">
			<input type="hidden" id="pop_hapthetas" name="pop_hapthetas">
			<input type="submit" value="Export as KML" onclick="serializedata();">
		</form>
	</div>
	</div>
  </body>
</html>
